package com.example.util;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 *该方法用于解析 HTTP 请求的参数，并将其转换为一个 Map<String, String> 以便后续使用
 *主要用于处理异步通知，例如支付宝、微信等支付平台的回调请求。
 * */
public class ParamsUtil {
    /**
     * 将异步通知的参数转换为Map
     */

    public static Map<String, String> ParamstoMap(HttpServletRequest request) throws UnsupportedEncodingException {
        System.out.print("start for request======================================================================================================》");
        StringBuilder sb = new StringBuilder();
        // 打印原始请求体（调试用）
        System.out.println("Raw request body: " + sb.toString());
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }
    public static Map<String,String>parseJsonBody(HttpServletRequest request) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (sb.length() == 0) {
            return new HashMap<>();
        }

        // 打印原始请求体（调试用）
        System.out.println("Raw request body: " + sb.toString());

        // 解析 JSON 为 Map
        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        Map<String, String> resultMap = new HashMap<>();
        for (String key : jsonObject.keySet()) {
            resultMap.put(key, jsonObject.getString(key));
        }

        return resultMap;
    }

}


